package dmitrygusev.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;


public class IOUtils {

	public static String readToEnd(String filename, String charset) throws FileNotFoundException,
			IOException, UnsupportedEncodingException {
		
		InputStream is = null;
		
		is = new FileInputStream(new File(filename));
		
		return IOUtils.readToEnd(is, charset);
	}

	public static String readToEnd(InputStream source, String charset)
			throws IOException, UnsupportedEncodingException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		byte[] buffer = new byte[1024];
		int bytesRead;
		
		try {
			while ((bytesRead = source.read(buffer)) != -1) {
				baos.write(buffer, 0, bytesRead);
			}
			
			return baos.toString(charset);
		} finally {
			if (source != null) {
				source.close();
			}
		}
	}

}
